<?php

namespace app\common\model;

use Jdy;
use think\Model;
use traits\model\SoftDelete;

class Custom extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'custom';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'createtime_text',
        'new_name',
    ];
    public function getNewNameAttr($v, $d)
    {

        return $d['name'] . '#' . $d['id'];
    }

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    protected static function init()
    {
        self::beforeInsert(function ($row) {
            $row->lasttime = time();
            if (!empty($row['phone'])) {
                // var_dump($row['phone']);
                $has = self::where('phone', trim($row['phone']))->value('id');
                // var_dump($has);
                if ($has) {
                    exception('该手机号客户已存在');
                }
            }
        });

        self::afterInsert(function ($row) {
            // if (empty($row['jdy_id']) && !empty($row['acct_id']) && ($row['acct_id'] == 50 || $row['acct_id'] == 67)) {
            //     $api = new Jdy();
            //     $api->addCustom($row);
            // }
        });

        self::afterUpdate(function ($row) {
            $change = $row->getChangedData();
            if (!empty($row['jdy_id']) && !empty($row['acct_id'] && ($row['acct_id'] == 50 || $row['acct_id'] == 67))) {
                if (isset($change['name']) || isset($change['phone']) || isset($change['address']) || isset($change['user_id'])) {
                    $api = new Jdy(['acct_id' => $row['acct_id']]);
                    $api->addCustom($row);
                }
            }
        });

        self::afterDelete(function ($row) {
            // if (!empty($row['jdy_id'])) {
            //     $api = new Jdy();
            //     $api->common('bd_customer', [$row['jdy_id']], 'delete');
            // }
        });
    }
}
